package com.appspot.kiyoshiro.kei3.service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.slim3.datastore.Datastore;
import org.slim3.jsp.Functions;

import com.google.appengine.api.datastore.Key;

import net.arnx.jsonic.JSON;

public class JsonService {

	private static final String TIME_STAMP_FORMAT = "yyyy/MM/dd HH:mm:ss";

	public enum JsonStatus {

		UNKNOWN("unknown"),
		SUCCESS("success"),
		INPUT_INVALID("input-invalid"),
		GOOGLE_AUTH_FAILED("google-auth-failed");

		private String val;

		private JsonStatus(String val) {
			this.val = val;
		}

		public String val() {
			return this.val;
		}
	}

	private static final String CONTENT_TYPE = "application/json";

	private static final String CHARSET = "UTF-8";

	private JSON json = new JSON() {
		// フォーマット可能なクラスに変換します（formatでのみ有効です）。
		// 例外が発生した場合、JSONExceptionでラップされ呼び出し元に通知されます。
		protected Object preformat(Context context, Object value)
				throws Exception {
			if(value instanceof JsonStatus){
				return ((JsonStatus) value).val();
			}
			if(value instanceof Key){
				return Datastore.keyToString((Key)value);
			}
			if(value instanceof Date){
				return new SimpleDateFormat(TIME_STAMP_FORMAT).format((Date)value);
			}
			if(value instanceof String){
				return Functions.h(value);
			}
			
			return super.preformat(context, value);
		}
	};

	private JsonStatus status;
	private Object data;

	public String toJson() {
		return json.format(this);
	}

	/**
	 * @param status
	 *            the status to set
	 */
	public void setStatus(JsonStatus status) {
		this.status = status;
	}

	/**
	 * @return the status
	 */
	public JsonStatus getStatus() {
		return status;
	}

	/**
	 * @param data
	 *            the data to set
	 */
	public void setData(Object data) {
		this.data = data;
	}

	/**
	 * @return the data
	 */
	public Object getData() {
		return data;
	}

	public void out(HttpServletResponse response) throws IOException {
		response.setContentType(CONTENT_TYPE);
		response.setCharacterEncoding(CHARSET);
		response.getWriter().print(this.toJson());
		response.flushBuffer();
	}

}
